package com.itc.bi.easyExcelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import org.apache.poi.ss.usermodel.CellType;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CustomInterceptor extends AnalysisEventListener<LinkedHashMap<Integer, Object>> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private Map<Integer, String> integerStringMap;

    private List<LinkedHashMap<String,Object>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        System.out.println("读取到一行表头数据: " + headMap);
        integerStringMap = ConverterUtils.convertToStringMap(headMap, context);
    }

    @Override
    public void invoke(LinkedHashMap<Integer, Object> data, AnalysisContext context) {
        LinkedHashMap<String, Object> stringObjectLinkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<Integer,Object> entry:data.entrySet()){
            Integer key = entry.getKey();
            Object value = entry.getValue();
            String title = integerStringMap.get(key);
            ReadCellData cell = (ReadCellData)context.readRowHolder().getCellMap().get(key);
            if(cell!=null){
                CellDataTypeEnum type = cell.getType();
                //这里注意 虽然是日期 但是 类型 存储的是number 因为excel 存储的就是number
                if(type.equals(CellDataTypeEnum.NUMBER)){
                    //特殊处理 时间格式的列 尝试转换为时间格式   若能转 则表示是时间格式
                    String format = cell.getDataFormatData().getFormat();
                    if(format.contains("yyyy") || format.contains("yyyy-m-d") || format.contains("yyyy-m-d h:mm")){

                    }
                }
            }
            stringObjectLinkedHashMap.put(title,value);
        }
        cachedDataList.add(stringObjectLinkedHashMap);
        System.out.println("读取到一行数据: " + data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("所有数据读取完毕");
    }
}

